<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Allows a template to be automatically loaded and displayed. Display can be
 * dynamically turned off in the controller methods, and the template file
 * can be overloaded.
 *
 * To use it, declare your controller to extend this class:
 * `class Your_Controller extends Template_Controller`
 *
 * $Id: template.php 4134 2009-03-28 04:37:54Z zombor $
 *
 * @package    Core
 * @author     Kohana Team
 * @copyright  (c) 2007-2008 Kohana Team
 * @license    http://kohanaphp.com/license.html
 */
abstract class Template_Controller extends Controller {

	// Default to do auto-rendering
	public $auto_render = TRUE;

	//BaseController variables
	public $title = '';
	public $subtitle = '';
	public $menu = '';
	
	public $profiler = FALSE;
	public $online_profiler = FALSE;
	
	public $db, $session, $user_messages, $auth, $wb_menu;
	public $logged_in = FALSE;
	
	
	/**
	 * Template loading and setup routine.
	 * 
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();

		// Load the template
		$this->template = new View(Kohana::config('admin.template').'/template', array('main' => array(), 'right' => array()));

		if ($this->auto_render == TRUE)
		{
			// Render the template immediately after the controller method
			Event::add('system.post_controller', array($this, '_render'));
		}
		
		//BaseController functions
		$this->_autoload();
		$this->_base_config();
		$this->_set_profiler();
		
		$this->_login_check();
		//$this->_upkeep();
	}

	/**
	 * Render the loaded template.
	 * 
	 * @return void
	 */
	public function _render()
	{
		if ($this->auto_render == TRUE)
		{
			$this->template->header = new View(Kohana::config('admin.template').'/parts/main_header');
			$this->template->header->menu = new View(Kohana::config('admin.template').'/parts/header_menu');
			$this->template->render(TRUE);
		}
	}
	
	/**
	 * Check if a user has logged in
	 * 
	 * @return void
	 */
	function _login_check()
	{
		if (($this->logged_in = $this->auth->logged_in())==FALSE)
		{
			if ( ! in_array($this->uri->rsegment(1), array('admin'))
				|| in_array($this->uri->rsegment(2), array('edit')))
			{
			     $this->session->set("requested_url","/".url::current()); // this will redirect from the login page back to this page/
			     url::redirect('/admin/login');				
			}
		}
		else
		{
			$this->user = $this->auth->get_user();
			
			$this->wb_menu = new WB_Menu();
			$this->wb_menu->build(Kohana::config('admin.navigation'), Kohana::config('admin.navigation_translate'));
			$this->wb_menu->select($this->menu);
		}
	}
	
	/**
	 * Autoloading libraries
	 * 
	 * @return void
	 */
	function _autoload()
	{
		$this->db = new Database();
		$this->session = Session::instance();
		$this->user_messages = new User_Message();
		$this->auth = new Auth();
		
		$this->wb_template = new WB_Template();
		//$this->wb_template->js('google','http://www.google.com/jsapi?key='. Kohana::config('gmaps.api_key'));
		//$this->wb_template->script('jquery','google.load("jquery", "1.3.1");');
		$this->wb_template->js('jquery-1.3.2.min');
		$this->wb_template->js('wb_admin');
		$this->wb_template->css('reset', 'reset.css');
		$this->wb_template->css('layout', 'layout.css');
		$this->wb_template->css('menu', 'menu.css');
		$this->wb_form = new WB_Form();
		$this->wb_db = new WB_Db($this->wb_form);
	}
	
	
	/**
	 * Setting basic php and template variables
	 * 
	 * @return void
	 */
	function _base_config()
	{
		setlocale(LC_ALL, "hu_HU");
		date_default_timezone_set('Europe/Budapest');
		ini_set('mbstring.internal_encoding', 'UTF-8');
		
		
		$this->menu = $this->uri->rsegment(1);
	}
	
	/**
	 * Set language
	 * 
	 * @param $lang
	 * @return string
	 */
	function _lang_config($lang=FALSE)
	{
		if ($lang) $this->session->set('locale.language', $lang);
		if ($this->session->get('locale.language')) Kohana::config_set('locale.language', array($this->session->get('locale.language')));
		else $this->session->set('locale.language', Kohana::config('locale.language.0'));
		
		$lang = Kohana::config('locale.language.0');
		$this->wb_template->js_var('lang', $lang);
		$this->db->query("SET lc_time_names = '".$lang."'");
		
		return $lang;
	}
	
	/**
	 * Set profiler
	 * 
	 * @return unknown_type
	 */
	function _set_profiler($profiler=NULL)
	{
		if (is_bool($profiler))
		{
			$this->online_profiler = TRUE;
			$this->profiler = TRUE;
		}
		if ($this->profiler && DEVSERVER || 
			$this->online_profiler && ! DEVSERVER) {
				$this->profiler = new Profiler;
			}
	}
	
	/**
	 * Sets the Swift 4 library
	 * 
	 * @return void
	 */
	function _set_email()
	{
		if ( ! empty($this->mailer)) return;
		
		require_once MODPATH.'/swift/libraries/swift_required.php';
		
		if ($this->http_host=='localhost')
			//Create the Transport
			$this->transport = Swift_SmtpTransport::newInstance('mail.t-online.hu', 25)
				->setUsername('thoer81@gmail.com')
				->setPassword('4pm6KfJd6K')
			;
		else
			$this->transport = Swift_MailTransport::newInstance();
		
		//Create the Mailer using your created Transport
		$this->mailer = Swift_Mailer::newInstance($this->transport);
	}
	
	function _new_message()
	{
		if (empty($this->mailer)) $this->_set_email();
		
		return Swift_Message::newInstance();
	}
	
	/**
	 * Handling database errors
	 * 
	 * @return unknown_type
	 */
	function _db_error()
	{
		$this->session->set_flash('function', $this->uri->string());
		$this->session->set_flash('errno', $this->db->call_function('errno'));
		$this->session->set_flash('error', $this->db->call_function('error'));
		$this->session->set_flash('query', $this->db->last_query());
		url::redirect('main/db_error');
	}
	
	/**
	 * Rendering data for Ajax operations
	 * 
	 * @param mixed $data
	 * @return void
	 */
	public function _render_json($data)
	{
		//if (expires::check(10) === FALSE) expires::set(10);
		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');
		
		$this->auto_render = FALSE;
		$view = new View('common/json');
		$view->data = $data;
		
		$view->render(TRUE);
	}
	
	/**
	 * Rendering data for Ajax operations
	 * 
	 * @param mixed $data
	 * @return void
	 */
	public function _render_autocompleter($data)
	{
		$this->auto_render = FALSE;
		$view = new View('common/autocompleter');
		$view->data = $data;
		
		$view->render(TRUE);
	}

} // End Template_Controller